/*
 * 文 件 名:  BaseController.java
 * 版    权:  kuanrf  Co., Ltd. Copyright YYYY-YYYY,  All rights reserved
 * 描    述:  <描述>
 * 修 改 人:  sheng.li
 * 修改时间:  2015年4月15日
 * 跟踪单号:  <跟踪单号>
 * 修改单号:  <修改单号>
 * 修改内容:  <修改内容>
 */
package com.cnpinxi.controller.base;


import com.cnpinxi.def.Constant;
import com.cnpinxi.domain.AdminUser;
import com.cnpinxi.domain.User;
import com.cnpinxi.log.LogFactory;
import com.cnpinxi.myRunTime.MyRunTimeExcption;
import com.cnpinxi.service.UserService;
import com.cnpinxi.service.WeChatService;
import com.cnpinxi.util.*;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;


/**
 * <一句话功能简述>
 * <功能详细描述>
 *
 * @author sheng.li
 * @version [版本号, 2015年4月15日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public abstract class BaseController {

    protected Logger logger = LogFactory.getLogger(getClass());
    @Autowired
    UserService userService;
    @Autowired
    WeChatService weChatService;

    protected void modifySession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(Constant.SESSION_KEY_USER_LOGIN);
        user = userService.getUserById(user.getTid());
        session.setAttribute(Constant.SESSION_KEY_USER_LOGIN, user);
    }

    protected User getUserBySession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(Constant.SESSION_KEY_USER_LOGIN);
        return user;
    }

    protected Map<String, String> showRequestParameters(HttpServletRequest request) {

        Enumeration<?> paramNames = request.getParameterNames();
        Map<String, String> map = new HashMap<String, String>();
        while (paramNames.hasMoreElements()) {

            String paramName = paramNames.nextElement().toString();
            String paramValue = request.getParameter(paramName);
            map.put(paramName, paramValue);
            System.out.println(paramName + "[:]" + paramValue);
        }

        try {
            AdminUser adminUser = (AdminUser) request.getSession().getAttribute(Constant.SESSION_KEY_ADMDIN_USER_LOGIN);
            if (adminUser != null) {
                map.put("operatorId", String.valueOf(adminUser.getTid()));
                map.put("operatorName", adminUser.getRealName());
            }

        } catch (Exception e) {
            logger.info(e.getMessage());
        }
        try {
            User user = (User) request.getSession().getAttribute(Constant.SESSION_KEY_USER_LOGIN);
            if (user != null) {
                map.put("userId", String.valueOf(user.getTid()));
            }

        } catch (Exception e) {
            logger.info(e.getMessage());
        }


        return map;
    }

    protected Map<String, String> upLoadFile(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            System.out.println(fileMap.size());
            for (String key : fileMap.keySet()) {
                System.out.println("key= " + key + " and value= " + map.get(key));
                String filePath = FileTools.getUniquenessName("") + FileTools.PICTURE_SUFFIX_JPG;
                System.out.println("filepath" + filePath);
                MultipartFile multipartFile = fileMap.get(key);
                System.out.println("file.getSize()===>>>" + multipartFile.getSize());
                byte[] bytes = multipartFile.getBytes();
                LoadPic.LoadPics(multipartFile, filePath);
            /*	BufferedOutputStream stream =
						new BufferedOutputStream(new FileOutputStream(new File("/static/images/"+filePath)));
				stream.write(bytes);
				stream.close();*/
                map.put(key, filePath);
            }

            //上传文件

        } catch (Exception e1) {
            System.out.println(e1.getMessage());
            e1.printStackTrace();
        }
        return map;
    }

    protected AdminUser getAdminUserBySession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        AdminUser adminUser = null;
        try {
            adminUser = (AdminUser) session.getAttribute(Constant.SESSION_KEY_ADMDIN_USER_LOGIN);
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyRunTimeExcption(e.getMessage());
        }
        return adminUser;


    }


    /**
     * 获取客户端浏览器来源是否是微信浏览器
     * (此功能暂时未完善)
     *
     * @param request
     * @return
     */
    protected boolean getBrowserSource(HttpServletRequest request) {
        String userAgent = request.getHeader("user-agent").toLowerCase();
        if (userAgent.indexOf("micromessenger") > -1) {
            logger.info("微信浏览器======》》》");
            return true;
        }
        logger.info("不是微信浏览器======》》》");
        return false;

    }


    /**
     * 判断客户端是否是移动端
     *
     * @param request
     * @return
     */
    protected boolean getIsMobile(HttpServletRequest request) {
        String userAgent = request.getHeader("user-agent");
        String[] agent = {
                "Android"
                , "iPhone"
                , "iPod"
                , "iPad"
                , "Windows Phone"
                , "MQQBrowser"};

        boolean flag = false;
        if (
                !userAgent.contains("Windows NT")
                        || (userAgent.contains("Windows NT") && userAgent.contains("compatible; MSIE 9.0;"))) {

            // 排除 苹果桌面系统
            if (!userAgent.contains("Windows NT") && !userAgent.contains("Macintosh")) {
                for (String item : agent) {
                    if (userAgent.contains(item)) {
                        flag = true;
                        break;
                    }
                }
            }
        }
        return flag;
    }

    /**
     * 微信授权
     *
     * @param request
     * @param response
     */

    protected void oauth2(HttpServletRequest request, HttpServletResponse response) {

        if (!getBrowserSource(request)) {
            logger.info("不是微信浏览器，不能鉴权");
            return;
        }
        String openId = (String) request.getSession().getAttribute("openId");
        if (StringUtils.isNotBlank(openId)) {
            logger.info("已经鉴权，不用再次鉴权=====》》》》》》" + openId);
            return;
        }
        String code = request.getParameter("code");
        if (StringUtils.isNotBlank(code)) {
            //获取openId
            getOpenId(request, code);
            return;
        }


        HttpServletRequest httpRequest = (HttpServletRequest) request;

        String toUrl = "http://" + request.getServerName() //服务器地址
               /* + ":"
                + request.getServerPort()           //端口号
                */
                + httpRequest.getContextPath()      //项目名称
                + httpRequest.getServletPath();      //请求页面或其他地址

        String queryStr = httpRequest.getQueryString();
        if (StringUtils.isNotBlank(queryStr)) {
            toUrl += "?" + queryStr; //参数
        }


        logger.info(" ===========================u==============================================>/n" + toUrl);
        String u = WeiXinUtils.oauth2(toUrl, WeiXinUtils.SNSAPI_BASE);
        logger.info(" ===========================u==============================================>/n" + u);
        try {
            response.sendRedirect(u);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    protected void getOpenId(HttpServletRequest request, String code) throws MyRunTimeExcption {
        if (StringUtils.isNotBlank(code)) {

            String openId = weChatService.getopenId(FixedData.ENTERPRISE_APP_ID, code);
            if (StringUtils.isBlank(openId)) {

                throw new MyRunTimeExcption("微信鉴权失败");
            }
            request.getSession().setAttribute(Constant.SESSION_OPEN_ID, openId);

        }
    }


    protected User getUserByOpenId(String openId) {
        if (StringUtils.isBlank(openId)) {
            return null;
        }
        User user = new User();
        user.setOpenId(openId);
        return userService.login(user);
    }

    protected void bindOpenId(HttpSession session, User user) {
        User user1 = null;
        if (StringUtils.isBlank(user.getOpenId())) {
            return;
        }
        if (StringUtils.isBlank(user.getPhone())) {
            return;
        }
        try {
            user1 = userService.getUserByPhone(user.getPhone());
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("Login bindOpenId");


        if (user1 == null) {



            user1 = new User();
            user1.setCreateTime(new Date());
            user1.setOpenId(user.getOpenId());
            user1.setPhone(user.getPhone());
            user1.setPassWord(MD5Tools.MD5("123456"));
            user1.setUserAddress(user.getUserAddress());
            user1.setUserName(user.getUserName());
            userService.regedit(user1);
            logger.info(user1.toString());
        }
        if (user1 != null) {
            if (StringUtils.isBlank(user1.getOpenId())) {
                user1.setOpenId(user.getOpenId());
                userService.modifyUser(user1);
            }
        }

        session.setAttribute(Constant.SESSION_KEY_USER_LOGIN, user1);

    }

}
